<template>
  <div class="ai-admin-container">
    <div class="chat-container">
      <div class="messages-wrapper">
        <van-list>
          <div
              v-for="(message, index) in messages"
              :key="index"
              :class="['message-bubble', message.role]"
          >
            <div class="message-content">
              <van-icon
                  v-if="message.role === 'assistant'"
                  name="manager"
                  class="message-icon"
              />
              <van-icon
                  v-else
                  name="user-circle"
                  class="message-icon"
              />
              <div class="text-content">
                {{ message.content }}
              </div>
            </div>
            <div class="message-time">
              {{ formatTime(message.timestamp) }}
            </div>
          </div>
        </van-list>
        <!-- 加载中的消息 -->
        <div v-if="isLoading" class="message-bubble assistant">
          <div class="message-content">
            <van-icon name="manager" class="message-icon" />
            <div class="text-content">
              {{ partialResponse }}<span class="cursor">|</span>
            </div>
          </div>
          <div class="message-time">
            {{ formatTime(new Date()) }}
          </div>
        </div>
      </div>

      <div class="input-area">
        <van-field
            v-model="userInput"
            placeholder="请输入管理指令..."
            rows="1"
            autosize
            type="textarea"
            class="input-field"
            @keyup.enter="sendMessage"
        >
          <template #button>
            <van-button
                size="small"
                type="primary"
                :loading="isLoading"
                :disabled="!userInput.trim()"
                @click="sendMessage"
            >
              发送
            </van-button>
          </template>
        </van-field>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, onUnmounted } from 'vue'
import { showToast, showFailToast } from 'vant'
import { _axios } from "../api/index.js"

// 响应式数据
const userInput = ref('')
const messages = ref([])
const isLoading = ref(false)
const partialResponse = ref('')
const abortController = ref(null)

// 初始化消息
const initMessages = () => {
  messages.value = [
    {
      role: 'assistant',
      content: '您好，我是AI超级管理员，请问有什么管理任务需要处理？',
      timestamp: new Date()
    }
  ]
}

// 发送消息到后端
const sendMessage = async () => {
  if (!userInput.value.trim() || isLoading.value) return

  const userMessage = {
    role: 'user',
    content: userInput.value,
    timestamp: new Date()
  }

  messages.value.push(userMessage)
  userInput.value = ''
  isLoading.value = true
  partialResponse.value = ''

  try {
    abortController.value = new AbortController()

    const response = await fetch(_axios.getUri() + '/admin/ai-management', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + localStorage.getItem('jwt'),
      },
      body: JSON.stringify({request: userMessage.content}),
      signal: abortController.value.signal
    })

    if (!response.ok) {
      showFailToast(`HTTP error! status: ${response.status}`)
      return
    }

    // 处理SSE流式响应
    const reader = response.body.getReader()
    const decoder = new TextDecoder('utf-8')

    while (true) {
      const {done, value} = await reader.read()
      if (done) break

      const chunk = decoder.decode(value)
      const lines = chunk.split('\n')

      for (const line of lines) {
        if (line.startsWith('data:')) {
          const data = line.substring(5).trim()
          if (data) {
            partialResponse.value += data
          }
        } else if (line.trim()) {
          partialResponse.value += line.trim()
        }
      }
    }

    // 流式输出完成，将完整响应添加到消息列表
    messages.value.push({
      role: 'assistant',
      content: partialResponse.value,
      timestamp: new Date()
    })

    partialResponse.value = ''
  } catch (error) {
    if (error.name === 'AbortError') {
      console.log('请求被取消')
      showToast('请求已取消')
    } else {
      console.error('请求失败:', error)
      showFailToast('请求失败，请重试')
      messages.value.push({
        role: 'assistant',
        content: '抱歉，处理您的请求时出现了问题，请稍后重试。',
        timestamp: new Date()
      })
    }
  } finally {
    isLoading.value = false
    abortController.value = null
  }
}

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    const container = document.querySelector('.messages-wrapper')
    if (container) {
      container.scrollTop = container.scrollHeight
    }
  })
}

// 格式化时间
const formatTime = (timestamp) => {
  return new Date(timestamp).toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 组件卸载时取消请求
onUnmounted(() => {
  if (abortController.value) {
    abortController.value.abort()
  }
})

// 初始化
onMounted(() => {
  initMessages()
  scrollToBottom()
})
</script>

<style scoped>
.ai-admin-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}

.chat-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.messages-wrapper {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
}

.message-bubble {
  margin-bottom: 16px;
  display: flex;
  flex-direction: column;
}

.message-bubble.assistant {
  align-items: flex-start;
}

.message-content {
  display: flex;
  max-width: 80%;
}

.message-bubble.user .message-content {
  flex-direction: row-reverse;
}

.message-icon {
  font-size: 24px;
  margin: 0 8px;
  color: #07c160;
}

.text-content {
  padding: 12px;
  border-radius: 8px;
  background-color: white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.message-bubble.user .text-content {
  background-color: #e1f3d8;
}

.message-time {
  font-size: 12px;
  color: #969799;
  margin-top: 4px;
  padding: 0 12px;
}

.input-area {
  background-color: white;
  padding: 12px;
  border-top: 1px solid #ebedf0;
}

.input-field {
  background-color: #f7f8fa;
  border-radius: 8px;
}

.cursor {
  animation: blink 1s infinite;
}

@keyframes blink {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0;
  }
}
</style>